package cn.kailangtu.serialutils.api;


import cn.kailangtu.commontools.AppVariable;
import cn.kailangtu.commontools.CommonUtils;

public class ComBase {
    ReceiveMsgListenerV2 commonMsglistener = null;


    protected boolean isOpen = false;
    protected byte address = 1;

    public boolean openSerialPort(String portName,int baudrate,int flags,
                                  ReceiveMsgListenerV2 commonMsgListener){
      //  if(SerialPortApi)
        open();
        isOpen = false;
        if(SerialPortApi.getInstance().isOpen()) {

            isOpen =  true;
        }
        this.commonMsglistener = commonMsgListener;
        return isOpen;
    }

    public boolean openSerialPort485(ReceiveMsgListenerV2 commonMsgListener)
    {
        this.commonMsglistener = commonMsgListener;
        return true;
    }

    private void open()
    {
        if(!SerialPortApi.getInstance().isOpen())
        {
            SerialPortApi.getInstance().openSerialPortV2("",256000,0);
        }

    }

    public byte[] sendData(byte[] data)
    {
        if(AppVariable.platform_version == 450)
        {
            //SerialPort485Manager.getInstance().sendString(address, CommonUtils.ByteArrayToHexString(data));

            return  SerialPort485Manager.getInstance().sendString(address,data);
        }
        else {
            DataVersion2 dv2 = DataVersion2.build(address, data);
            SerialPortApi.getInstance().addSendString(dv2.getCmdString());
        }
        return null;
    }

    public void receiveData(byte[] data)
    {
        if(commonMsglistener != null)
        {
            commonMsglistener.onReceiveData(data.clone());
        }
    }

    public boolean isOpen() {
        return isOpen;
    }

    public void close()
    {
        commonMsglistener = null;
        isOpen = false;
    }

    protected byte getBaudrateByte(int baudrate)
    {
        byte result = 0x05;
        switch(baudrate){
            case 1200:
                result = 0x00;
                break;
            case 2400:
                result = 0x01;
                break;
            case 4800:
                result = 0x02;
                break;
            case 9600:
                result = 0x03;
                break;
            case 19200:
                result = 0x04;
                break;
            case 38400:
                result = 0x05;
                break;
            case 57600:
                result = 0x06;
                break;
            case 115200:
                result  =0x07;
                break;
        }

        return result;
    }
}
